package socket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
// [V] I didn't make changes there
public class ClientSocket {
	private ObjectOutputStream out;
	private ObjectInputStream in;
	 //Something strange in readMessage was, we don't need it here, because you return String from readMessage.
	private BufferedReader input;
	
	public void startClient() throws ClassNotFoundException {
		Socket requestSocket = null;
		String message;
		boolean inChat;
		
		
		try {
			requestSocket = new Socket("localhost", 2003);
			System.out.println("Connected to localhost in port 2003");
			
			in = new ObjectInputStream(requestSocket.getInputStream());
			out = new ObjectOutputStream(requestSocket.getOutputStream());
			out.flush();
			input = new BufferedReader(new InputStreamReader(System.in));
			
			inChat = authentication();
			
			while (inChat) {
				sendMessage(input.readLine());
				message = readMessage();
				
				if (message.equals("goodbye"))
					break;
				
			} 
			
		} catch (UnknownHostException unknownHost) {
			System.out.println("You are trying to connect to an unknown host!");
		} catch (IOException ioException) {
			ioException.printStackTrace();
		} finally {
			try {
				in.close();
				out.close();
				requestSocket.close();
			} catch (IOException ioException) {
				ioException.printStackTrace();
			}
		}
	}
	
	private boolean authentication() throws IOException, ClassNotFoundException{
		String message = readMessage();
		String command;
		boolean tryAuthentication = true;
		
		while(tryAuthentication) {
			if (message.equals("Enter login and password:")) {
				System.out.print("login: ");
				sendMessage(input.readLine());
				System.out.print("password: "); 
				sendMessage(input.readLine());
			}
			
			message = readMessage();
			
			if (message.equals("Welcome to chat")){
				break;
			} else {
				command = input.readLine();
				sendMessage(command);
				
				if (command.equals("n"))
					return false;
				
				message = readMessage();
			}
		}
		return true;
	}
	
	private void sendMessage(final String msg) throws IOException {
		out.writeObject(msg);
		out.flush();
	}
		
	private String readMessage() throws IOException, ClassNotFoundException {
	    String message = (String) in.readObject();
	    System.out.println("server> " + message);
	    return message;
	}

}
